package com.lyy;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class Test1 {
    public static void main(String[] args) {
        //获取连接
        //Jedis jedis=new Jedis("localhost",6379);
        Jedis jedis = getJedisClien();//使用jedis连接池来获取jedis
        //设置字符串值
        jedis.set("username","zhangsan");
        //带过期时间设置值
        jedis.setex("password",10,"123");
        //获取字符串
        System.out.println(jedis.get("username"));

        //存储hash
        jedis.hset("student","name","zhangsan");
        jedis.hset("student","age","18");
        //获取map中的某个值
        System.out.println(jedis.hget("student","age"));
        //获取整个map
        Map<String, String> map = jedis.hgetAll("student");
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            System.out.println(entry.getKey()+":"+entry.getValue());
        }

        //存储列表
//        jedis.lpush("list","a");
//        jedis.lpush("list","b");
//        jedis.rpush("list","c");
        //list范围获取
        List<String> list = jedis.lrange("list", 0, -1);
        System.out.println(list);
        //list弹出
        String ele = jedis.lpop("list");
        System.out.println(ele);
        String ele2 = jedis.rpop("list");
        System.out.println(ele2);

        //set集合类型数据
        jedis.sadd("myset","java","php","c_sharp");
        jedis.srem("myset","java");//移除set集合中的某个元素
        Set<String> myset = jedis.smembers("myset");//获取set集合的全部元素
        System.out.println(myset);

        //有序set存储,根据给定的分数排序，分数越大越靠后
        jedis.zadd("mysortSet",1,"a");
        jedis.zadd("mysortSet",10,"c");
        jedis.zadd("mysortSet",100,"b");
        System.out.println(jedis.zrange("mysortSet",0,-1));

        //指定某个key的过期时间
        jedis.expire("student",15);
        jedis.close();//使用连接池获取到的连接,调用close方法就是把连接归还连接池
    }

    /**
     * 用jedis连接池来获取jedis对象
     * @return
     */
    public static Jedis getJedisClien(){
        JedisPoolConfig config=new JedisPoolConfig();
        config.setMaxTotal(10);
        config.setMaxIdle(10);
        JedisPool pool=new JedisPool(config,"localhost",6379);
        return pool.getResource();
    }
}
